var http = require('http');
var cookie = require('cookie');

module.exports = function(app) {
    
    app.post('/MK',function(req, res, next){
        
        var cookies = cookie.parse(req.headers.cookie,{});
        var json = "";
        
        
        var headers = {};
        var token = cookies['x-auth-token'];
        if(!token){
//        	res.redirect("/gams-login");
//        	return;
        	token = {};
        }
        
        
        req.on('data',function(data){
            json += data;
        });
        
        req.on('end',function(){
        	json = JSON.parse(json);
           // var json = eval('('+ json +')');
            var hostInfos = global.CONFIG.servers[json.serverName || "default"];
            
            var options = {
                host: hostInfos.host,
                port: hostInfos.port,
                protocol: hostInfos.protocol,
                path: json.url,
                method: json.method || 'post',
                headers: {
                    'cookie': req.headers.cookie,
                    'x-auth-token':token,
                    'Content-Type' : 'application/json'
                }
            };
            
            var request = http.request(options, function (response) {
                res.statusCode = response.statusCode;
                response.pipe(res);
            }).on('error', function (e) {
                res.statusCode = 503;
                res.end();
            });
			var inputs;
			if(!json["data"]){
				inputs = "";
			}else if(typeof json["data"] === "string"){
				inputs = json["data"];
			}else{
				inputs = JSON.stringify(json["data"]);
			}
			if (inputs) {
				request.write(inputs);
			}
        
            request.end();
        });
        
    });
};